package com.example.student_system.controller;

import com.example.student_system.entity.Student;
import com.example.student_system.service.StudentService;

import org.apache.catalina.connector.Response;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentWebController {

    private final StudentService studentService;

    public StudentWebController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List<Student> listStudents(Model model) {
        return studentService.getAllStudents();
    }

    @GetMapping("/new")
    public String showCreateForm(Model model) {
        model.addAttribute("student", new Student());
        model.addAttribute("isNew", true);
        return "students/form";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        Student student = studentService.getStudentById(id);
        model.addAttribute("student", student);
        model.addAttribute("isNew", false);
        return "students/form";
    }

    @PostMapping("/save")
    public ResponseEntity<String> saveStudent(@ModelAttribute Student student) {
        studentService.saveStudent(student);

        return ResponseEntity.ok("学生信息保存成功");
    }

    @GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            studentService.deleteStudent(id);
            redirectAttributes.addFlashAttribute("message", "学生删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/students";
    }

    @GetMapping("/search")
    public String searchStudents(@RequestParam(required = false) String name,
            @RequestParam(required = false) String className,
            Model model) {
        if (name != null && !name.isEmpty()) {
            model.addAttribute("students", studentService.getStudentsByName(name));
        } else if (className != null && !className.isEmpty()) {
            model.addAttribute("students", studentService.getStudentsByClass(className));
        } else {
            model.addAttribute("students", studentService.getAllStudents());
        }
        return "students/list";
    }

    @ModelAttribute("today")
    public LocalDate getToday() {
        return LocalDate.now();
    }
}